<?php
// need to fix when login is invalid
require_once("database.php");
session_start();

if($_POST && isset($_POST['username']) && isset($_POST['password'])){

  // Get salt
  $salty = query_select("
    SELECT salt
    FROM user
    WHERE username = '" . $_POST['username'] . "'"
  );
  
  // If username doesn't exist, go back to login
  if(count($salty) == 0){
    header('location: index.php');
    exit;
  }

  // Sanitize Inputs
  $safe_username = sql_escape($_POST['username']);
  $md5_password = md5($salty[0]['salt'] . $_POST['password']);
  unset($_POST['password']);
  $safe_md5_password = sql_escape($md5_password);
  
  // Query Database
  $sqluser = "
    SELECT *
    FROM user
    WHERE username = '" . $safe_username . "'
    AND password = '" . $safe_md5_password . "'";
	
  $users = query_select($sqluser);
  
  // Check returned values
  if(count($users) == 0){
    // Invalid login
    header('location: index.php');
    exit;
  }
  else {
    // Valid login
    session_start();
    $_SESSION['user'] = $users[0]['id'];
    $_SESSION['admin'] = $users[0]['isadmin'];
	
    header('location: index.php');
    exit;
  }
}
else{
  header('location: index.php');
  exit;
}

?>
